package cn.xenosp.server.config.mybatis;

import cn.dev33.satoken.exception.NotWebContextException;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.xenosp.server.module.user.entity.SysUser;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 项目名： service-web
 * 包路径： cn.xenosp.server.config.mybatis
 * 作者：   TongHui
 * 创建时间: 2024-09-02 17:55
 * 描述: 自动填充字段
 * 版本: 1.0
 */

@Slf4j
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时的填充策略
     * this.strictInsertFill(metaObject,"字段名", 字段值类型.class, 字段值);
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            Date date = new Date();
            this.strictInsertFill(metaObject,"createTime", Date.class, date);
            this.strictInsertFill(metaObject,"updateTime", Date.class,date);

            SysUser user = getUser();
            this.strictInsertFill(metaObject,"creator", String.class, user.getUsername());
            this.strictInsertFill(metaObject,"updater", String.class, user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新时的填充策略

    /**
     * 更新时的填充策略
     *  this.strictUpdateFill(metaObject, "字段名", 字段值类型.class, 字段值);
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            this.strictInsertFill(metaObject,"updateTime", Date.class, new Date());

            SysUser user = getUser();
            this.strictInsertFill(metaObject,"updater", String.class, user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private SysUser getUser(){
        try {
            return (SysUser) StpUtil.getSession().get("user");
        }catch (NotWebContextException e){
            log.warn("未获取用户信息"+e.getMessage());
            SysUser user = new SysUser();
            user.setUsername("system");
            return user;
        }
    }
}
